package com.csnj.core.Srvs.SysManager.impl;

import com.csnj.common.constant.UserConstant;
import com.csnj.common.exception.IRCException;
import com.csnj.common.jwt.*;
import com.csnj.common.utils.BaseContextHandler;
import com.csnj.core.Srvs.SysManager.AuthSrvs;
import com.csnj.core.Srvs.SysManager.SysUserSrvs;
import com.csnj.core.constant.CoreConstants;
import com.csnj.core.entity.SysUser;
import com.csnj.core.exception.PasswordErrorException;
import com.csnj.core.exception.SystemErrorException;
import com.csnj.core.exception.TokenInvalidException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthSrvs {
    @Autowired
    SysUserSrvs userSrvs;

    @Value("${jwt.expire}")
    private Integer userExpireTime;
    @Value("${jwt.rsa-secret}")
    private String userSecret;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT);

    @Override
    public String validate(JwtAuthenticationRequest authenticationRequest) throws IRCException {
        SysUser user = userSrvs.getUserByUsername(authenticationRequest.getUsername());
        if (user != null && encoder.matches(authenticationRequest.getPassword(), user.getPassword())) {
            JwtInfo jwtInfo = new JwtInfo(user.getId().toString(), user.getUsername());
            BaseContextHandler.setUserID(jwtInfo.getUserId());
            BaseContextHandler.setUsername(jwtInfo.getUsername());
            try {
                return SimpleJWT.generateTokenBy(jwtInfo, userExpireTime, userSecret);
            } catch (Exception e) {
                throw new SystemErrorException(CoreConstants.MSG_SYSTEM_ERROR);
            }
        }
        throw new PasswordErrorException(CoreConstants.MSG_PASSWORD_ERROR);
    }

    @Override
    public JwtInfo validate(String token) throws TokenInvalidException {
        try {
           return SimpleJWT.parseJWTToken(token, userSecret);
        } catch (Exception e) {
           throw new TokenInvalidException(CoreConstants.MSG_TOKEN_INVALID);
        }
    }

    @Override
    public void SaveLoginLog(String userID, String ip) {
        SysUser u = new SysUser();
        u.setId(Integer.valueOf(userID));
        u.setUpdateTime(new Date());
        u.setLoginIp(ip);
        userSrvs.updateSelectiveById(u);
    }

    @Override
    public String refresh(String oldToken) throws TokenInvalidException {
        try {
            return SimpleJWT.generateTokenBy(SimpleJWT.parseJWTToken(oldToken, userSecret), userExpireTime, userSecret);
        } catch (Exception e) {
            throw new TokenInvalidException(CoreConstants.MSG_TOKEN_INVALID);
        }
    }
}
